package com.example.component.handler

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.component.R
import kotlin.concurrent.thread

class HandlerActivity : AppCompatActivity() {
    private val updateText = 1


    private val handler = Handler(Looper.getMainLooper()) {
        when (it.what) {
            updateText -> {
                val textView = findViewById<TextView>(R.id.textView)
                textView.text = "Hello World"
            }
        }
        true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_handler)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val changeTextBtn = findViewById<Button>(R.id.changeTextBtn)
        changeTextBtn.setOnClickListener {
            thread {
                /**
                 * 发送消息到主线程，
                 * 主线程处理消息，更新UI
                 */
                val msg = Message()
                msg.what = updateText
                handler.sendMessage(msg)
            }
        }
    }
}